
function goFirst() {
	var participants = gapi.hangout.getParticipants();
	
	var id = gapi.hangout.getParticipantId();
	
	var pack = new ExtGames.Pack({
		decks: NUM_DECKS
	});
	
	var delta = {};
	delta['turn'] = '0';
	delta['turnId'] = id;
	delta['firstPlayer'] = id;
	delta['participants'] = JSON.stringify(participants);
	delta['deck'] = pack.getCardString();
	gapi.hangout.data.submitDelta(delta);
}

function submitMayIRequest() {
	var o = {
		id: getMyId(),
		turn: gapi.hangout.data.getState()['turnId']
	};
	
	var delta = {};
	delta['mayi'] = JSON.stringify(o);
	gapi.hangout.data.submitDelta(delta);
}

function nextRound() {
	
	var opp = getOpponents();
	
	var firstP = gapi.hangout.data.getState()['firstPlayer'];
	var ids = [];
	ids.push(getMyId());
	for (var i = 0; i < opp.length; i++) {
		ids.push(opp[i].id);
	}
	
	var index = ids.indexOf(firstP);
	index = (index+1)%ids.length;
	firstP = ids[index];
	
	var delta = {};
	delta['turn'] = '0';
	delta['turnId'] = firstP;
	delta['firstPlayer'] = firstP;
	delta['deck'] = game.pack.getCardString();
}

function endTurn() {
	
	var nextOpp = getNextOpponent();
	
	var delta = {};
	delta['turn'] = ''+nextOpp['turn'];
	delta['turnId'] = nextOpp['id'];
	gapi.hangout.data.submitDelta(delta);
}

function getTurnName() {
	return getName(gapi.hangout.data.getState()['turnId']);
}

function isTurn() {
	var turnId = gapi.hangout.data.getState()['turnId'];
    var id = gapi.hangout.getParticipantId();
    return (turnId == id);
}

function getTurnIndex() {
	var participants = eval('('+gapi.hangout.data.getState()['participants']+')');
    
	var i = 0;
	while (participants[i].hangoutId != getMyId()) {
		i++;
	}
	
	var turnId = gapi.hangout.data.getState()['turnId'];
	var j = 0;
	while (participants[j].hangoutId != turnId) {
		j++;
	}
    
    var index = (j - i);
    if (index < 0) {
    	index += gapi.hangout.getParticipants().length;
    }
    
    return index;
}

function drawCard(details) {
		
	details.id = getMyId();
	
	gapi.hangout.data.submitDelta({
		draw: JSON.stringify(details)
	});
}

function discard(details) {
	
	details.id = getMyId();
	
	gapi.hangout.data.submitDelta({
		discard: JSON.stringify(details)
	});
}

function submitMayICards(id, details) {
	details.id = id;
	
	gapi.hangout.data.submitDelta({
		draw: JSON.stringify(details)
	});
}

function getNextOpponent() {
	var participants = eval('('+gapi.hangout.data.getState()['participants']+')');
	
	var i = 0;
	while (participants[i].hangoutId != getMyId()) {
		i++;
	}
	i++;
	
	if (i >= participants.length) {
		i = 0;
	}
	
	return {
		turn: i,
		id: participants[i].hangoutId
	}
}

function getOpponentIndex(id) {
	var opp = getOpponents();
	for (var i = 0; i < opp.length; i++) {
		if (opp[i].id == id) {
			return (i+1);
		}
	}
}

function getOpponents() {
	var participants = eval('('+gapi.hangout.data.getState()['participants']+')');
	
	var i = 0;
	while (participants[i].hangoutId != getMyId()) {
		i++;
	}
	i++;
	
	var opp = [];
	
	for (var j = 0; j < (participants.length-1); j++) {
		if (i >= participants.length) {
			i = 0;
		}
		
		opp[j] = {
			id:	participants[i].hangoutId,
			name: participants[i].displayName
		};
		
		i++;
	}
	
	return opp;
}

function getMyId() {
	return gapi.hangout.getParticipantId();
}

function getMe() {
	return gapi.hangout.getParticipantById(gapi.hangout.getParticipantId());
}

function getName(id) {
	return gapi.hangout.getParticipantById(gapi.hangout.getParticipantId()).displayName;
}

function getNumP() {
	return gapi.hangout.getParticipants().length;
}

function submitScorecard(score) {
	var opp = getOpponents();
	
	var scorecard = {};
	scorecard[getMyId()] = scores[0];
	for (var i = 0; i < opp.length; i++) {
		scorecard[opp[i].hangoutId] = scores[i+1];
	}
	
	gapi.hangout.data.submitDelta({
		scores: JSON.stringify(scorecard)
	});
}



// Callback functions for events created by the hangout
function apiReady() {
  console.log("API is ready");
}


function stateUpdated(adds, removes, delta, metadata) {

	if (adds != null && adds.length > 0) {
		console.log('Added to state ('+adds.length+'): ');
		for (var i = 0; i < adds.length; i++) {
			console.log("\t"+adds[i].key+": "+adds[i].value);
			
			var added = adds[i];
			
			if (added.key == 'deck') {
				if (game == null) {
					game = new ExtGames.Game({
						cards: added.value,
						decks: NUM_DECKS
					});		
					game.newGame();
					game.launch();	
				}
				else {
					game.pack.createCards({
						cards: added.value
					});
				}
				
				document.getElementById('startDiv').style.display = 'none';
			}
			else if (added.key == 'turnId') {
				if (game != null) {
					game.nextTurn();
				}
			}
			else if (added.key == 'draw') {
				if (added.value.id != getMyId()) {
					game.drewCard(eval('('+added.value+')'));
				}
			}
			else if (added.key == 'discard') {
				if (added.value.id != getMyId()) {
					game.discardedCard(eval('('+added.value+')'));
				}
			}
			else if (added.key == 'scores') {
				game.updateScores(eval('('+added.value+')'));
			}
			else if (added.key == 'firstPlayer') {
				if (game != null) {
					Ext.getCmp('nextRoundButton').enable();
				}
				
			}
			else if (added.key == 'mayi') {
				if (isTurn() && added.value.turn == getMyId()) {
					game.mayIRecieved(added.value.id);
				}
			}
		}
	}
	if (removes != null && removes.length > 0) {
		console.log("Removed from state: ");
		for (var i = 0; i < removes.length; i++) {
			console.log("\t"+removes[i]);
		}
		
	}
}

function participantsUpdated(participantsArray) {
  
}

// A function to be run at app initialization time which registers our callbacks
function init() {
		
  console.log("Init app.");
  gapi.hangout.data.addStateChangeListener(stateUpdated);
  gapi.hangout.addParticipantsListener(participantsUpdated);

  // This application is pretty simple, but use this special api ready state
  // event if you would like to any more complex app setup.
  gapi.hangout.addApiReadyListener(apiReady);  
}

gadgets.util.registerOnLoadHandler(init);

